package org.six11.ss.server;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.six11.ss.server.bean.Person;
import org.six11.util.adt.MultiState;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class LoginWebActionHandler extends WebActionHandler {

  /**
   * @param actionName
   * @param jsp
   * @param ms
   */
  public LoginWebActionHandler(String actionName, String jsp, MultiState ms) {
    super(actionName, jsp, ms);
  }

  /**
   * User provides params: username, password.
   */
  @Override
  public void handle(HttpServletRequest req, HttpServletResponse resp, ServletContext context)
      throws ServletException, IOException {
    String nextJsp = jsp;
    String user = req.getParameter("username");
    String pass = req.getParameter("password");
    bug("You provided: " + user + "/" + pass);
    if (user == null || pass == null) {
      // TODO: no error, just forward to login.jsp.
      error(req, "Howdy!");
    } else if (user.length() == 0 || pass.length() == 0) {
      // TODO: set the error message saying no username or password provided.
      error(req, "Please give me your username and password.");
    } else {
      // Attempt to pull the user out of the DB. Things could go wrong:
      // 1. There could be no user with that username.
      // 1a. TODO: Perhaps the user entered a nickname instead. Check that out.
      // 2. There could be a user with that username but the password is wrong.
      Person person = (Person) getHibernate().createQuery(
          "from Person as person where person.username = ?").setString(0, user).uniqueResult();
      if (person == null) {
        // TODO: no user in the DB with that name.
        bug("No user with that name.");
        error(req, "I can't find a player with the username '" + user
            + "'. Maybe you're typing in a nickname instead? They're not the same.");
      } else if (!person.getPassword().equals(pass)) {
        // TODO: username valid but PW is wrong.
        bug("Valid username, but password is wrong.");
        error(req, "I found that player. Unfortunately, the password is wrong.");
      } else {
        // TODO: all good.
        bug("OK, log " + person.getNick() + " in.");
        req.getSession().setAttribute("userName", person.getUsername());
        req.getSession().setAttribute("userID", "" + person.getId());
        req.getSession().setAttribute("sketches", getBrowseHandler().getRecentSketches());
        nextJsp = "/index.jsp";
      }
    }
    forwardTo(nextJsp, req, resp, context);
  }

}
